package com.it.you.base.regular;

import cn.hutool.core.map.MapUtil;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 替换 {} 中的内容
 */
public class RegularTest1 {
    public static void main(String[] args) {
        String mes = "{秒杀数量}{单位}商品享受秒杀价，因为库存或限购原因{原价数量}{单位}原价购买。";
        Map<String, String> tipsMap = MapUtil.newHashMap();
        tipsMap.put("单位", "片");
        tipsMap.put("秒杀数量", "10");
        tipsMap.put("原价数量", "20");
        String tips = processMsg(tipsMap, mes);
        System.out.println(tips);

        String result = "您已被【{店铺名称}】限制购买，请联系客服处理";
        StringBuilder storeErrorMsg = new StringBuilder();
        storeErrorMsg.append("湖北");
        Map<String, String> valMap = MapUtil.newHashMap();
        valMap.put("店铺名称", storeErrorMsg.toString());
        String r = processMsg2(valMap, result);
        System.out.println(r);
    }

    public static String processMsg(Map<String, String> valMap, String msg) {
        Pattern pattern = Pattern.compile("\\{.*?}");
        Matcher slashMatcher = pattern.matcher(msg);
        int start = 0;
        while (slashMatcher.find(start)) {
            start = slashMatcher.end();
            String key = slashMatcher.group();
            String val = valMap.get(key.substring(1, key.length() - 1));
            if (val == null) {
                continue;
            }
            msg = msg.replace(key, val);
        }
        return msg;
    }

    public static String processMsg2(Map<String, String> valMap, String msg) {
        String patternRex = "\\{[^{].*?[^}]}";
        Pattern pattern = Pattern.compile(patternRex);
        Matcher slashMatcher = pattern.matcher(msg);
        int start = 0;
        while (slashMatcher.find(start)) {
            start = slashMatcher.end();
            String key = slashMatcher.group();
            String val = valMap.get(key.substring(1, key.length() - 1));
            if (val == null) {
                continue;
            }
            msg = msg.replace(key, val);
        }
        return msg;
    }
}
